<!-- 表单弹窗 -->
<style>
    .layui-form-item {
        margin-top: 20px;
    }
    .layui-form-item .layui-form-label{
        width: 90px;
    }
    .layui-form-item .layui-input-block {
        margin-left: 120px;
    }
    .layui-form-item .layui-inline {
        margin-right: 0;
    }
    .form-group-bottom {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 10px 20px;
        background-color: #fff;
        box-shadow: 0 -1px 2px 0 rgba(0, 0, 0, .05);
        z-index: 9;
    }
    body .tox-tinymce-aux {
        z-index: 19892000;
    }

    .photosList{width: 92px; display: inline-block; margin: 0 10px 10px 0;}
    .photosList .layui-upload-img{width: 92px; height: 92px; cursor: zoom-in;}
    .photosList a{width: 100%;}
</style>
<form id="mxForm" lay-filter="mxForm" class="layui-form" style="background:#f5f7f9;">
    <input name="id" type="hidden"/>
    <div class="layui-fluid" style="padding-bottom: 75px;">
        <div class="layui-card">
            <div class="layui-card-body">
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">所属分类</label>
                    <div class="layui-input-block">
                        <div id="classifyParentSel" class="mx-xmselect-tree"></div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">文章标题</label>
                    <div class="layui-input-block">
                        <input name="title" class="layui-input" autocomplete="off" placeholder="请输入文章标题" lay-verType="tips" lay-verify="required" required/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">META关键词</label>
                    <div class="layui-input-block">
                        <input name="keywords" class="layui-input" autocomplete="off" placeholder="多个关键词用英文状态 , 号分割"/>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">META描述</label>
                    <div class="layui-input-block">
                        <textarea name="description" placeholder="请输入META描述" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">缩略图</label>
                    <div class="layui-input-block">
                        <input name="image" class="layui-input" autocomplete="off" placeholder="请输入缩略图地址"/>
                        <button type="button" class="layui-btn layui-btn-normal imageMore"><i class="layui-icon">&#xe681;</i>上传图片</button>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章内容</label>
                    <div class="layui-input-block">
                        <textarea class="TinyEditor" name="content" class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline layui-col-md4">
                        <label class="layui-form-label">文章作者</label>
                        <div class="layui-input-block">
                            <input name="author" class="layui-input" autocomplete="off" placeholder="请输入文章作者"/>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md4">
                        <label class="layui-form-label">文章来源</label>
                        <div class="layui-input-block">
                            <input name="source" class="layui-input" autocomplete="off" placeholder="请输入文章来源"/>
                        </div>
                    </div>
                    <div class="layui-inline layui-col-md4">
                        <label class="layui-form-label">浏览量</label>
                        <div class="layui-input-block">
                            <input name="click" placeholder="请输入浏览量" type="number" class="layui-input" autocomplete="off" lay-verType="tips" lay-verify="number"/>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">多图上传</label>
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-normal" id="photos">上传多张图片</button>
                        <input type="hidden" name="photos[]"/>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            <p>图片大小控制在2M以内（可拖拽图片调整显示顺序）</p>
                            <div class="layui-upload-list" id="photosView"></div>
                        </blockquote>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">音频上传</label>
                    <div class="layui-input-block">
                        <input name="audio" class="layui-input" autocomplete="off" placeholder="请输入音频文件地址"/>
                        <button type="button" class="layui-btn layui-btn-normal" id="audioBtn"><i class="layui-icon">&#xe67c;</i>上传音频</button>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">视频上传</label>
                    <div class="layui-input-block">
                        <input name="video" class="layui-input" autocomplete="off" placeholder="请输入视频文件地址"/>
                        <button type="button" class="layui-btn layui-btn-normal" id="videoBtn"><i class="layui-icon">&#xe67c;</i>上传视频</button>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">排序权重</label>
                    <div class="layui-input-block">
                        <input name="weight" placeholder="请输入排序权重" type="number" class="layui-input" autocomplete="off" lay-verType="tips" lay-verify="number" value="50"/>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="form-group-bottom text-center">
        <button class="layui-btn" lay-filter="mxSubmit" lay-submit>保存</button>
        <button class="layui-btn layui-btn-primary" type="button" mx-event="closeDialog">取消</button>
    </div>
</form>

<script type="text/javascript" src="/static/assets/libs/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="/static/assets/libs/sortable/sortable.min.js"></script>
<script>
    layui.use(['layer', 'form', 'admin', 'xmSelect', 'upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var xmSelect = layui.xmSelect;
        var upload = layui.upload;

        //图片上传
        upload.render({
            elem: '.imageMore',
            url: "{:url('mxadmin/upload/upload')}", //改成您自己的上传接口
            acceptMime: 'image/*',
            size: 2048, //限制文件大小，单位 KB
            done: function(res){
                if (res.code === 1) {
                    layer.msg(res.msg, {icon: 1});
                    this.item.prev('input').val(res.data.filePath);
                    this.item.after(' <a href="'+res.data.filePath+'" target="_blank"><img src="'+res.data.filePath+'" height="38"></a>');
                } else {
                    layer.msg(res.msg, {icon: 5, anim: 6});
                }
            }
        });

        //多图上传
        upload.render({
            elem: '#photos',
            url: "{:url('mxadmin/upload/upload')}", //改成您自己的上传接口
            multiple: true,
            acceptMime: 'image/*',
            size: 2048, //限制文件大小，单位 KB
            done: function(res){
                if (res.code === 1) {
                    layer.msg(res.msg, {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 5, anim: 6});
                }
                var i = Math.floor(Math.random() * (99999999 - 100 + 1) ) + 100;
                $('#photosView').append('<p class="photosList"><img src="'+ res.data.filePath +'" class="layui-upload-img"><a id="removeImg" class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i>删除</a><input type="hidden" name="photos['+ i +']" value="' + res.data.filePath + '"/></p>');
            },
        });

        // 音频上传
        upload.render({
            elem: '#audioBtn',
            url: "{:url('mxadmin/upload/upload_file_same')}", //改成您自己的上传接口
            accept: 'audio', //音频文件
            acceptMime: 'audio/*',
            done: function(res){
                if (res.code === 1) {
                    layer.msg(res.msg, {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 5, anim: 6});
                }
                layui.$('[name="audio"]').val(res.data.filepath);
            }
        });

        // 视频上传
        upload.render({
            elem: '#videoBtn',
            url: "{:url('mxadmin/upload/upload_file_same')}", //改成您自己的上传接口
            accept: 'video', //视频文件
            acceptMime: 'video/*',
            done: function(res){
                if (res.code === 1) {
                    layer.msg(res.msg, {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 5, anim: 6});
                }
                layui.$('[name="video"]').val(res.data.filepath);
            }
        });

        /* 点击图片放大 */
        layer.photos({
            photos: '#photosView',
            shade: .5,
            closeBtn: true
        });

        // 渲染富文本编辑器
        tinymce.init({
            selector: '.TinyEditor',
            height: 525,
            branding: false,
            language: 'zh_CN',
            plugins: 'code print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
            toolbar: 'fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap pagebreak | anchor codesample ltr rtl',
            content_style: "img {max-width:100%;}",
            convert_urls: false,
            images_upload_handler: function (blobInfo, succFun, failFun) {
                var xhr, formData;
                var file = blobInfo.blob();//转化为易于理解的file对象
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', "{:url('mxadmin/upload/upload_editor_same')}");
                xhr.onload = function() {
                    var json;
                    if (xhr.status != 200) {
                        failFun('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.location != 'string') {
                        failFun('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    succFun(json.location);
                };
                formData = new FormData();
                formData.append('file', file, file.name );//此处与源文档不一样
                xhr.send(formData);
            },
            setup: function(editor){
                editor.on('change',function(){ editor.save(); }); //ajax提交表单自动同步textarea
            }
        });

        var mData = admin.getLayerData('#mxForm').formdata;  // 列表页面传递的数据，#mxForm这个只要写弹窗内任意一个元素的id即可
        // 回显数据
        form.val('mxForm', mData);

        if (mData) {
            // 上传图片小图显示
            var imageValue = $('.imageMore').prev('input').val();
            if (imageValue) {
                $('.imageMore').after(' <a href="'+imageValue+'" target="_blank"><img src="'+imageValue+'" height="38"></a>');
            }
        } else {
            //浏览量随机数值
            $('[name="click"]').val(parseInt(Math.random() * (100 - 800 + 1) + 800));
        }

        if (mData && mData.photos) {
            var str = mData.photos.map(function (item) {
                return $('#photosView').append('<p class="photosList"><img src="'+ item +'" class="layui-upload-img"><a id="removeImg" class="layui-btn layui-btn-sm layui-btn-danger"><i class="layui-icon">&#xe640;</i>删除</a><input type="hidden" name="photos[]" value="' + item + '"/></p>');
            });
        }
        $("body").on("click","#removeImg",function(){
            $(this).parent().remove();
        });

        // 表单提交事件
        form.on('submit(mxSubmit)', function (data) {
            data.field.category_id = insXmSel.getValue('valueStr');
            layer.load(2);
            var url = mData ? "{:url('cms/article/edit')}" : "{:url('cms/article/add')}";
            $.post(url, data.field, function (res) {
                layer.closeAll('loading');
                if (res.code === 1) {
                    layer.msg(res.msg, {icon: 1});
                    admin.putLayerData('formOk', true, '#mxForm');  // 设置操作成功的标识，#mxForm这个只要写弹窗内任意一个元素的id即可
                    admin.closeDialog('#mxForm');  // 关闭页面层弹窗
                } else {
                    layer.msg(res.msg, {icon: 5, anim: 6});
                }
            }, 'json');
            return false;
        });

        // 渲染下拉树
        var insXmSel = xmSelect.render({
            el: '#classifyParentSel',
            layVerify: 'required',
            layVerType: 'tips',
            height: '400px',
            initValue: mData ? [mData.category_id] : [],
            model: {label: {type: 'text'}},
            prop: {
                name: 'name',
                value: 'id'
            },
            radio: true,
            clickClose: true,
            filterable: true,
            filterMethod: function(val, item, index, prop){
                if(item.name.toLowerCase().indexOf(val.toLowerCase()) != -1){ //名称中包含的大小写都搜索出来
                    return true;
                }
                return false; //其他的就不要了
            },
            searchTips: '请输入关键词进行搜索',
            tree: {
                show: true,
                indent: 15,
                strict: false,
                expandedKeys: true
            },
            data: {:json_encode($category)},
        });
    });

    // 图片拖拽排序
    var photosView = document.getElementById('photosView');
    new Sortable(photosView, {
        animation: 200,
    });
</script>
